package com.kalvan.core.response;

import com.kalvan.core.exception.BizException;
import com.kalvan.core.exception.ReturnCode;
import com.kalvan.core.system.SystemUtil;
import lombok.Getter;

import javax.validation.constraints.NotBlank;

/**
 * 基础返回对象
 *
 * @author chenliang
 */
@Getter
public class Result<T> implements java.io.Serializable {

    private static final long serialVersionUID = 1L;
    /**
     * 系统编号,默认使用application-name
     */
    @NotBlank
    protected String system;
    /**
     * 返回码,0000表示请求处理成功,具体业务状态需要再解析data的数据
     */
    @NotBlank
    protected String code;

    /**
     * 返回描述,定义类为ReturnCode
     */
    @NotBlank
    protected String desc;

    /**
     * 返回业务数据
     */
    protected T data;

    /**
     * @param code 返回码
     * @param desc 返回描述
     * @return 返回结果对象
     */
    public static Result buildResult(String code, String desc) {
        Result result = new Result();
        result.setSystem(SystemUtil.constants != null ? SystemUtil.constants.getName() : null);
        result.setCode(code);
        result.setDesc(desc);
        return result;
    }

    /**
     * 根据返回码解析返回对象
     *
     * @param returnCode 返回码对象
     * @return 返回结果对象
     */
    public static Result buildResult(ReturnCode returnCode) {
        Result result = new Result();
        result.setSystem(returnCode.getSystem());
        result.setCode(returnCode.getCode());
        result.setDesc(returnCode.getDesc());
        return result;
    }

    /**
     * 根据biz异常解析返回对象
     *
     * @param exception bizException
     * @return 返回结果对象
     */
    public static Result buildResult(BizException exception) {
        Result result = new Result();
        result.setSystem(exception.getSystem());
        result.setCode(exception.getCode());
        result.setDesc(exception.getDesc());
        return result;
    }

    /**
     * 返回处理成功结果,默认使用0000
     *
     * @return 返回结果对象
     */
    public static Result buildSuccess() {
        Result result = new Result();
        result.setSystem(SystemUtil.constants != null ? SystemUtil.constants.getName() : null);
        result.setCode("0000");
        result.setDesc("处理成功");
        return result;
    }

    public Result setSystem(String system) {
        this.system = system;
        return this;
    }

    public Result setCode(String code) {
        this.code = code;
        return this;
    }

    public Result setDesc(String desc) {
        this.desc = desc;
        return this;
    }

    public Result setData(T data) {
        this.data = data;
        return this;
    }

    /**
     * 是否返回成功业务码,默认使用0000
     *
     * @return true /false
     */
    public boolean success() {
        return "0000".equals(code);
    }

}
